//
//  CYHujiVC.m
//  CreditAddressBook
//
//  Created by Mosu&Cuu on 16/6/13.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "CYHujiVC.h"
#import "LEUnitView+LE.h"
#import "CYCreditTool.h"
#import "CustomIOSAlertView.h"
#import "UIImageView+WebCache.h"
#import "MWPhotoBrowser.h"
#import "LEPhotoBrowserTool.h"
#import "CYLoginHttpTool.h"
#import "CYUser.h"
#import "CYJsonInfo.h"
#import "NSObject+MJKeyValue.h"
#import "LEImagePickerTool.h"
#import "MBProgressHUD+LE.h"
#import "CYDiscoveryHttpTool.h"
#import "UIButton+WebCache.h"

@interface CYHujiVC ()
@property (weak, nonatomic) IBOutlet UIView *jiatingsubmitView;
@property (weak, nonatomic) IBOutlet UIButton *baipaiBtn;
@property (weak, nonatomic) IBOutlet UIButton *shouchiBtn;
@property (weak, nonatomic) IBOutlet UILabel *hujistatuesLab;
@property (nonatomic, strong) NSString *baipaiStr;
@property (nonatomic, strong) NSString *baipaiUrl;
@property (nonatomic, strong) NSString *shouchiStr;
@property (nonatomic, strong) NSString *shouchiUrl;
@property (nonatomic, strong) NSArray *jiatingArr;
@property (nonatomic, strong) NSMutableArray *jiatingsubmitArr;
@property (nonatomic, strong) NSMutableDictionary *hujiDic;
@property (weak, nonatomic) IBOutlet UIView *hujirecordView;
@property (weak, nonatomic) IBOutlet UILabel *hujirecordLab;
@property (nonatomic, strong) NSMutableArray *recordimageUrls;
@property (weak, nonatomic) IBOutlet UIButton *baipaibtn;
@property (weak, nonatomic) IBOutlet UIButton *shouchibtn;
@property (weak, nonatomic) IBOutlet UIButton *jiatingbtn1;
@property (weak, nonatomic) IBOutlet UIButton *jiatingbtn2;


@end

@implementation CYHujiVC

- (void)viewDidLoad {
     [super viewDidLoad];
     self.title = @"户籍";
     
     [_baipaibtn sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/huji/1.png"] forState:UIControlStateNormal];
     [_shouchibtn sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/huji/2.png"] forState:UIControlStateNormal];
     [_jiatingbtn1 sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/huji/3.png"] forState:UIControlStateNormal];
     [_jiatingbtn2 sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/huji/3.png"] forState:UIControlStateNormal];
     
     UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0,0,50,30)];
     rightButton.titleLabel.textColor = [UIColor blackColor];
     [rightButton addTarget:self action:@selector(submitclick) forControlEvents:UIControlEventTouchUpInside];
     [rightButton setTitle:@"确定" forState:UIControlStateNormal];
     UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightButton];
     self.navigationItem.rightBarButtonItem= rightItem;

     NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:@"hujiImage.plist"];
     _baipaiStr = [dictionary objectForKey:@"baipaiUrl"];
     _shouchiStr = [dictionary objectForKey:@"shouchiUrl"];
     _jiatingArr = [dictionary objectForKey:@"jiatingUrl"];
     
     if (_baipaiStr) {
          //          [_zhengshuBtn setImage:sd_imageURLForState:(UIControlState)state forState:UIControlStateNormal];
          [_baipaiBtn sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://image.credit-manage.com/%@",_baipaiStr]] forState:UIControlStateNormal];
     }
     if (_shouchiStr) {
          [_shouchiBtn sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://image.credit-manage.com/%@",_shouchiStr]] forState:UIControlStateNormal];
          
     }
     if (_jiatingArr.count) {
          _hujistatuesLab.text = @"已上传，再次上传将会重新更新此类";
          _hujistatuesLab.textColor = [UIColor redColor];
          
     }
     
     _hujiDic = [[NSMutableDictionary alloc]init];
     _jiatingsubmitArr = [[NSMutableArray alloc]init];
     _recordimageUrls = [[NSMutableArray alloc]init];
     
     
     [self setupUploadView];
     [self setrecordView];
    // Do any additional setup after loading the view from its nib.
}

-(void)setrecordView{
     
     // image 前缀
     NSString *preFixString = @"http://image.credit-manage.com/";
     // 屏幕的宽度 (也是承载imageView的view的宽度)
     CGFloat screenWidth = [[UIScreen mainScreen] bounds].size.width;
     // image各个边界的间隔
     CGFloat space = 10.f;
     // imageview的width (设定为5张)
     CGFloat imgWidth = (screenWidth - space * 6 ) / 5;
     // imageview的height
     CGFloat imgHeight = _hujirecordView.frame.size.height - space * 2;
     // 由于是xib + 手码, 代码获取xib控件的frame 必须在主线程中获取
     dispatch_async(dispatch_get_main_queue(), ^{
          CYUser *user = [CYLoginHttpTool userData].user;
          [CYHttpTool postWithURL:[CYURL shared].getProveInfoPics params:@{@"userId":user.userId,@"token":user.token} success:^(id json) {
               //        CYLog(@"json = %@",json);
               CYJsonInfo *jsoninf = [CYJsonInfo objectWithKeyValues:json];
               NSMutableArray *data = jsoninf.data;
               for (NSDictionary *dic in data) {
                    // 取网络图片地址
                    NSString *provePicAddress = [dic objectForKey:@"provePicAddress"];
                    //取type
                    NSInteger type = [[dic objectForKey:@"type"] integerValue];
                    switch (type) {
                         case 6
                              :
                              [_recordimageUrls addObject:provePicAddress];
                              break;
                    }
               }
               
               for (int i = 0; i < _recordimageUrls.count; i++ ) {
                    // image的url string
                    NSString *imgUrlString = [_recordimageUrls objectAtIndex:i];
                    imgUrlString = [preFixString stringByAppendingString:imgUrlString];
                    // 创建imageView
                    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(space + (imgWidth + space) * i, space, imgWidth, imgHeight)];
                    imgView.backgroundColor = [UIColor whiteColor];
                    // 此处你可使用SDWebImage来加载
                    [imgView sd_setImageWithURL:[NSURL URLWithString:imgUrlString]];
                    [_hujirecordView addSubview:imgView];
               }
               if (_recordimageUrls.count){
                    _hujirecordLab.hidden = YES;
                    UITapGestureRecognizer *tag = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(photoBrowser:)];
                    [_hujirecordView addGestureRecognizer:tag];
               }
               
          } failure:^(NSError *error) {
               
          }];
          
     });
     
}

/**
 *  图片浏览器
 */
- (void)photoBrowser:(UITapGestureRecognizer *)tag {
     CYLog(@"recordimage = %@",_recordimageUrls);
     NSArray *urls = _recordimageUrls;
     MWPhoto *photo = nil;
     NSMutableArray *photos = [NSMutableArray array];
     for (NSString *url in urls) {
          photo = [MWPhoto photoWithURL:CYURLWithService(url)];
          [photos addObject:photo];
     }
     [LEPhotoBrowserTool showPhotoBrowserWithController:self photos:photos];
}



-(void)submitclick{
     
     [_hujiDic removeAllObjects];
     
     if (_baipaiUrl) {
          [_hujiDic setObject:_baipaiUrl forKey:@"baipaiUrl"];
          
     }else if (!_baipaiUrl && _baipaiStr){
          [_hujiDic setObject:_baipaiStr forKey:@"baipaiUrl"];
          
     }if (_shouchiUrl) {
          [_hujiDic setObject:_shouchiUrl forKey:@"shouchiUrl"];
          
     }else if (!_shouchiUrl&&_shouchiStr){
          [_hujiDic setObject:_shouchiStr forKey:@"shouchiUrl"];
          
     }
     if (_jiatingsubmitArr.count) {
          [_hujiDic setObject:_jiatingsubmitArr forKey:@"jiatingUrl"];
          
     }else if (!_jiatingsubmitArr.count && _jiatingArr.count){
          [_hujiDic setObject:_jiatingArr forKey:@"jiatingUrl"];
     }
     
     if (_hujiDic.count != 0) {
     
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
     NSString *plistPath1= [paths objectAtIndex:0];
     NSLog(@"%@",plistPath1);
     //得到完整的路径名
     NSString *fileName = [plistPath1 stringByAppendingPathComponent:@"hujiImage.plist"];
     //NSMutableDictionary *myDic = [[NSMutableDictionary alloc]init];
     //[myDic setValuesForKeysWithDictionary:cityDic];
     NSFileManager *fm = [NSFileManager defaultManager];
     
     if ([fm createFileAtPath:fileName contents:nil attributes:nil] ==YES) {
          [_hujiDic writeToFile:fileName atomically:YES];
          NSLog(@"文件写入完成");
          CYLog(@"huji = %@",_hujiDic);
          [[NSNotificationCenter defaultCenter] postNotificationName:@"CYPersonalNotification" object:nil userInfo:nil];
           [self.navigationController popViewControllerAnimated:YES];
         }
     }else{
          CYAlertView(@"请最少提交一张图");
          
     }

     
}
- (void)setupUploadView {
     //
     [LEUnitView imageScrollView:self.jiatingsubmitView controller:self block:^(LEUnitView *unitView, LEUnitCell *cell, UIImage *image) {
          [CYCreditTool uploadPicImage:image success:^(NSString *imageUrl) {
               [_jiatingsubmitArr addObject:imageUrl];
               cell.ratio = 1;
          } failure:^(NSError *error) {
               //删除
               [unitView deleteLastCell];
          } uploadProgress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
               CGFloat a = totalBytesWritten;
               CGFloat b = totalBytesExpectedToWrite;
               cell.ratio = a/b - .01;
          }];
     } cellClick:^(LEUnitView *unitView, LEUnitCell *cell) {
     }];
}


- (IBAction)baipaiClick:(id)sender {
     [self.view.window endEditing:YES];
     [LEImagePickerTool select2ImageWithController:self edit:YES completion:^(UIImage *image) {
          [MBProgressHUD showMessage:@"处理中..." toView:self.view];
          [CYDiscoveryHttpTool uploadUserImage:image button:sender success:^(NSString *imagePath) {
               [MBProgressHUD hideHUDForView:self.view animated:YES];
               _baipaiUrl= imagePath;
               //weakself.model.certificateNoFAddress = imagePath;
          } failure:^(NSString *message, NSError *error) {
               [MBProgressHUD hideHUDForView:self.view animated:YES];
               if (message) {
                    [MBProgressHUD showError:message];
               }
          }];
     }];

}

- (IBAction)shouchiClick:(id)sender {
     [self.view.window endEditing:YES];
     [LEImagePickerTool select2ImageWithController:self edit:YES completion:^(UIImage *image) {
          [MBProgressHUD showMessage:@"处理中..." toView:self.view];
          [CYDiscoveryHttpTool uploadUserImage:image button:sender success:^(NSString *imagePath) {
               [MBProgressHUD hideHUDForView:self.view animated:YES];
               _shouchiUrl = imagePath;
               //weakself.model.certificateNoFAddress = imagePath;
          } failure:^(NSString *message, NSError *error) {
               [MBProgressHUD hideHUDForView:self.view animated:YES];
               if (message) {
                    [MBProgressHUD showError:message];
               }
          }];
     }];

}

- (IBAction)baipai:(id)sender {
     UIImageView *shareView = [[UIImageView alloc] init];
     [shareView sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/huji/1.png"]];
     //    CGFloat ratio = shareView.height / shareView.width;
     //    CGFloat height = CYScreeSize.height - 130;
     CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
     CGFloat w = CYScreeSize.width - 32;
     shareView.frame = CGRectMake(0, 0, w, self.view.height-160);
     alertView.containerView = shareView;
     alertView.buttonTitles = @[@"知道了"];
     
     [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
     }];
     [alertView show];

}
- (IBAction)shouchi:(id)sender {
     UIImageView *shareView = [[UIImageView alloc] init];
     [shareView sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/huji/2.png"]];
     //    CGFloat ratio = shareView.height / shareView.width;
     //    CGFloat height = CYScreeSize.height - 130;
     CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
     CGFloat w = CYScreeSize.width - 32;
     shareView.frame = CGRectMake(0, 0, w, self.view.height-160);
     alertView.containerView = shareView;
     alertView.buttonTitles = @[@"知道了"];
     
     [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
     }];
     [alertView show];

}
- (IBAction)chengyuan1:(id)sender {
     UIImageView *shareView = [[UIImageView alloc] init];
     [shareView sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/huji/3.png"]];
     //    CGFloat ratio = shareView.height / shareView.width;
     //    CGFloat height = CYScreeSize.height - 130;
     CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
     CGFloat w = CYScreeSize.width - 32;
     shareView.frame = CGRectMake(0, 0, w, self.view.height-160);
     alertView.containerView = shareView;
     alertView.buttonTitles = @[@"知道了"];
     
     [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
     }];
     [alertView show];

}
- (IBAction)chengyuan2:(id)sender {
     UIImageView *shareView = [[UIImageView alloc] init];
     [shareView sd_setImageWithURL:[NSURL URLWithString:@"http://www.credit-manage.com:8058/apppic/huji/4.png"]];
     //    CGFloat ratio = shareView.height / shareView.width;
     //    CGFloat height = CYScreeSize.height - 130;
     CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
     CGFloat w = CYScreeSize.width - 32;
     shareView.frame = CGRectMake(0, 0, w, self.view.height-160);
     alertView.containerView = shareView;
     alertView.buttonTitles = @[@"知道了"];
     
     [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
     }];
     [alertView show];

}
- (IBAction)chengyuan3:(id)sender {
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
